package com.cash.app.utils

import android.content.ContentResolver
import android.database.Cursor
import android.net.Uri
import android.provider.Telephony
import com.cash.app.application.MyApplication
import com.cash.app.constant.AppConstant
import com.cash.app.constant.AppConstant.SMS_TYPE_IN
import com.cash.app.constant.AppConstant.SMS_TYPE_OTHER
import com.cash.app.constant.AppConstant.SMS_TYPE_OUT
import com.cash.app.manager.GlobalConfigManager
import com.cash.app.manager.model.ThirdSmsData
import com.cash.app.manager.model.ThirdSmsInfo
import java.util.Calendar

object SmsUtils {

    private const val SMS_URI = "content://sms"
    private const val MAX_SMS_COUNT = 6000 // max 6000
    private const val MONTHS_AGO = 6 // 6 months ago

    fun getSmsMessages(): ThirdSmsData {
        val smsList = mutableListOf<ThirdSmsInfo>()
        val contentResolver = MyApplication.appContext.contentResolver
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.MONTH, -MONTHS_AGO)
        val sixMonthsAgo = calendar.timeInMillis

        // Get keywords from both sources
        val keywords = (AppConstant.SMS_KEYWORDS + GlobalConfigManager.getSmsKeyword()).distinct()

        val cursor = querySms(contentResolver, sixMonthsAgo)
        cursor?.use {
            var count = 0
            while (cursor.moveToNext() && count < MAX_SMS_COUNT) {
                val sms = extractSmsInfo(cursor)
                // Filter messages containing keywords
                if (sms != null && containsKeywords(sms.third_content, keywords)) {
                    smsList.add(sms)
                    count++
                }
            }
        }

        return ThirdSmsData(smsList)
    }

    private fun querySms(contentResolver: ContentResolver, startTime: Long): Cursor? {
        val uri = Uri.parse(SMS_URI)
        val projection = arrayOf(
            Telephony.Sms._ID,
            Telephony.Sms.ADDRESS,
            Telephony.Sms.PERSON,
            Telephony.Sms.BODY,
            Telephony.Sms.DATE,
            Telephony.Sms.TYPE
        )
        val selection = "${Telephony.Sms.DATE} >= ?"
        val selectionArgs = arrayOf(startTime.toString())
        val sortOrder = "${Telephony.Sms.DATE} DESC"

        return try {
            contentResolver.query(
                uri, projection, selection, selectionArgs, sortOrder
            )
        } catch (e: Exception) {
            null
        }
    }

    private fun extractSmsInfo(cursor: Cursor): ThirdSmsInfo? {
        return try {
            val address =
                cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)) ?: ""
            val person = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.PERSON)) ?: ""
            val body = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.BODY)) ?: ""
            val date = cursor.getLong(cursor.getColumnIndexOrThrow(Telephony.Sms.DATE))
            val type = when (cursor.getInt(cursor.getColumnIndexOrThrow(Telephony.Sms.TYPE))) {
                Telephony.Sms.MESSAGE_TYPE_INBOX -> SMS_TYPE_IN
                Telephony.Sms.MESSAGE_TYPE_SENT -> SMS_TYPE_OUT
                else -> SMS_TYPE_OTHER
            }

            ThirdSmsInfo(
                third_name = person,
                third_phone = address,
                third_content = body,
                third_send_time = (date / 1000).toInt(), // Convert milliseconds to seconds
                third_type = type
            )
        } catch (e: Exception) {
            null
        }
    }

    private fun containsKeywords(content: String, keywords: List<String>): Boolean {
        val lowerContent = content.lowercase()
        return keywords.any { keyword ->
            lowerContent.contains(keyword.lowercase())
        }
    }
} 